package com.yhsimon.realm.member.controller;

import com.alibaba.fastjson.JSON;
import com.yhsimon.realm.member.dto.user.UserDto;
import com.yhsimon.realm.member.entity.OssFile;
import com.yhsimon.realm.member.entity.user.UserEntity;
import com.yhsimon.realm.member.service.OssTemplate;
import com.yhsimon.realm.member.service.UserService;
import com.yhsimon.realm.member.utils.AuthContextUtils;
import com.yhsimon.realm.member.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/member/file")
@Slf4j
public class FileController {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 上传头像
     * @param file
     * @param userId
     * @param request
     * @return
     */
    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId, HttpServletRequest request) {
        log.info("[uploadAvatar]  file: {}", file);
        String folderName = "user/userId-" + userId + "/avatar";
        String fileName = file.getName();
        OssFile ossFile = ossTemplate.upLoadFile(folderName, fileName, file);
        String filePath = ossFile.getFilePath();
        if (ossFile.getFilePath().length() > 1) {
            filePath = filePath.substring(1);
        }
        // 具有时效性的url
        // String imgUrl = ossTemplate.getPresignedObjectUrl("public", filePath, 7 * 24 * 60 * 60);
        // 1. 获取图片地址
        String imgUrl = ossFile.getDomain() + "/" + filePath;
        log.info("[uploadAvatar]  imgUrl: {}", imgUrl);
        UserEntity userEntity = userService.getById(Long.parseLong(userId));
        userEntity.setAvatar(imgUrl);
        // 2. 更新数据库
        userService.updateById(userEntity);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userEntity,userDto);
        // 3. 更新本地缓存
        AuthContextUtils.setUserInfo(userDto);
        // 4. 更新redis缓存
        // 4.1 先获取token
        String token = request.getHeader("token");
        // 4.2 更新redis中的user缓存
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(userDto), 30, TimeUnit.MINUTES);
        log.info("[uploadAvatar]  userAvatarUrl缓存： {}", AuthContextUtils.getUserInfo().getAvatar());
        return R.ok("头像上传成功");
    }

    /**
     * 上传文章图片
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/uploadArticleImage")
    public R uploadArticleImage(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {
        log.info("[uploadAvatar]  file: {}", file);
        String folderName = "user/userId-" + userId + "/article";
        String fileName = file.getName();
        OssFile ossFile = ossTemplate.upLoadFile(folderName, fileName, file);
        String filePath = ossFile.getFilePath();
        if (ossFile.getFilePath().length() > 1) {
            filePath = filePath.substring(1);
        }
        String imgUrl = ossFile.getDomain() + "/" + filePath;
        log.info("[uploadAvatar]  imgUrl: {}", imgUrl);
        Map<String,String> map=new HashMap<>();
        map.put("imgUrl",imgUrl);
        map.put("desc",file.getOriginalFilename());
        return R.ok("图片上传成功").put("data",map);
    }
}
